-- ============================================
-- SERVEUR BANQUE - SNOUB CASINO
-- A faire tourner en permanence sur un computer dedie (pas besoin
-- de monitor), relie au reseau via un Wired Modem.
-- Gere le solde de TOUS les joueurs, repond aux demandes des
-- autres computers (guichet + machines de jeu) via rednet.
-- ============================================

local PROTOCOL = "snoub_banque"
local FILE = "soldes.dat"
local DEFAULT_BALANCE = 0

local modem = peripheral.find("modem")
if not modem then
    error("Aucun modem trouve ! Attache un Wired Modem a ce computer et fais un clic-droit dessus pour l'activer.")
end
rednet.open(peripheral.getName(modem))

local function loadAll()
    if not fs.exists(FILE) then return {} end
    local f = fs.open(FILE, "r")
    local content = f.readAll()
    f.close()
    local ok, data = pcall(textutils.unserialize, content)
    if ok and type(data) == "table" then return data end
    return {}
end

local function saveAll(data)
    local f = fs.open(FILE, "w")
    f.write(textutils.serialize(data))
    f.close()
end

local balances = loadAll()

local function getBalance(player)
    return balances[player] or DEFAULT_BALANCE
end

local function setBalance(player, amount)
    balances[player] = math.floor(amount)
    saveAll(balances)
end

local function countPlayers()
    local n = 0
    for _ in pairs(balances) do n = n + 1 end
    return n
end

print("=== Serveur Banque Snoub Casino ===")
print("Protocole : " .. PROTOCOL)
print("Joueurs enregistres : " .. countPlayers())
print("En attente de requetes...")

while true do
    local senderId, message = rednet.receive(PROTOCOL)

    if type(message) == "table" and message.action then
        local response = { ok = true }

        if message.action == "get" then
            response.balance = getBalance(message.player)

        elseif message.action == "add" then
            local current = getBalance(message.player)
            local newBal = current + (message.amount or 0)
            if newBal < 0 then
                response.ok = false
                response.error = "Solde insuffisant"
                response.balance = current
            else
                setBalance(message.player, newBal)
                response.balance = newBal
            end

        elseif message.action == "set" then
            setBalance(message.player, message.amount or 0)
            response.balance = getBalance(message.player)

        elseif message.action == "leaderboard" then
            local list = {}
            for name, bal in pairs(balances) do
                table.insert(list, { player = name, balance = bal })
            end
            table.sort(list, function(a, b) return a.balance > b.balance end)
            local limit = message.amount or 10
            local top = {}
            for i = 1, math.min(limit, #list) do
                top[i] = list[i]
            end
            response.list = top

        elseif message.action == "list" then
            response.balances = balances

        else
            response.ok = false
            response.error = "Action inconnue : " .. tostring(message.action)
        end

        rednet.send(senderId, response, PROTOCOL)
        print(os.date("%H:%M:%S") .. " " .. tostring(message.action) .. " " ..
              tostring(message.player) .. " -> " .. tostring(response.balance))
    end
end